package vip.xiaonuo.biz.modular.rewardslog.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import vip.xiaonuo.biz.modular.appletuser.entity.AppletUser;
import vip.xiaonuo.biz.modular.hiddenreport.entity.HiddenReport;
import vip.xiaonuo.biz.modular.rewardslog.entity.RewardsLog;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import vip.xiaonuo.biz.modular.rewardslog.enums.ReportExceptionEnum;
import vip.xiaonuo.biz.modular.rewardslog.enums.RewardsTypeEnum;
import vip.xiaonuo.biz.modular.rewardslog.mapper.RewardsLogMapper;
import vip.xiaonuo.biz.modular.rewardslog.service.RewardsLogService;
import org.springframework.stereotype.Service;
import vip.xiaonuo.biz.modular.watchtask.entity.Task;
import vip.xiaonuo.biz.modular.wechat.constant.WechatConstant;
import vip.xiaonuo.biz.modular.wechat.domain.dto.WechatCommissionDTO;
import vip.xiaonuo.biz.modular.wechat.domain.resp.WechatTransferQueryDetailResp;
import vip.xiaonuo.biz.modular.wechat.domain.resp.WechatTransferResp;
import vip.xiaonuo.biz.modular.wechat.service.WechatTransferService;
import vip.xiaonuo.common.enums.CommonStatusEnum;
import vip.xiaonuo.common.exception.CommonException;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 奖励记录(RewardsLog)表服务实现类
 *
 * @author h
 * @since 2025-11-21 14:24:38
 */
@Slf4j
@Service("rewardsLogService")
public class RewardsLogServiceImpl extends ServiceImpl<RewardsLogMapper, RewardsLog> implements RewardsLogService {
    @Resource
    private WechatTransferService wechatTransferService;

    @Override
    public void reportRewards(HiddenReport hiddenReport,AppletUser appletUser) {
        this.sendRewards(appletUser,hiddenReport.getHiddenRewards().longValue(),RewardsTypeEnum.REPORT.getValue(),hiddenReport.getReportId());
    }

    @Override
    public void taskRewards(Task task, AppletUser appletUser) {
        this.sendRewards(appletUser,task.getRewards().longValue(),RewardsTypeEnum.TASK.getValue(),task.getTaskId());
    }

    @Override
    public RewardsLog getByCode(String rewardsCode) {
        RewardsLog rewardsLog = this.baseMapper.queryDetailByCode(rewardsCode);
        if (ObjectUtil.isEmpty(rewardsLog)){
            throw new CommonException(ReportExceptionEnum.QUERY_FAIL.getMessage());
        }
        //查询转账状态
        log.info("微信红包查询请求 code==="+ rewardsLog.getRewardsCode());
        WechatTransferQueryDetailResp wechatTransferQueryDetailResp = wechatTransferService.queryDetail(rewardsLog.getRewardsCode());
        log.info("微信红包查询返回 WechatTransferQueryDetailResp==="+ JSON.toJSONString(wechatTransferQueryDetailResp));
        if (!wechatTransferQueryDetailResp.getCode().equals(WechatConstant.RESP_SUCCESS_CODE_200)){
            throw new CommonException(ReportExceptionEnum.REWARD_FAIL.getMessage());
        }
        //回填奖励信息
        rewardsLog.setDetailStatus(wechatTransferQueryDetailResp.getDetailStatus());
        this.baseMapper.updateById(rewardsLog);
        return rewardsLog;
    }

    /**
     * 调用转账接口
     * @param appletUser
     * @param rewards
     * @param rewardsType
     * @param bizId
     */
    private void sendRewards(AppletUser appletUser,Long rewards,Integer rewardsType,String bizId) {
        String rewardsCode=getMerNum();
        RewardsLog rewardsLog=new RewardsLog();
        if(ObjectUtil.equal(RewardsTypeEnum.REPORT.getValue(),rewardsType)){
            rewardsLog.setReportId(bizId);
        }
        if(ObjectUtil.equal(RewardsTypeEnum.TASK.getValue(),rewardsType)){
            rewardsLog.setTaskId(bizId);
        }
        rewardsLog.setRewardsCode(rewardsCode);
        rewardsLog.setRewardsType(rewardsType);
        rewardsLog.setRewards(rewards.intValue());
        rewardsLog.setUserId(appletUser.getUserId());

        WechatCommissionDTO wechatCommissionDTO =new WechatCommissionDTO();
        wechatCommissionDTO.setOpenId(appletUser.getOpenId());
        wechatCommissionDTO.setRewardNo(rewardsCode);
        wechatCommissionDTO.setCommissionAmount(rewards);
        log.info("微信红包发送请求 wechatCommissionDTO==="+ JSON.toJSONString(wechatCommissionDTO));
        WechatTransferResp wechatTransferResp =wechatTransferService.transfer(wechatCommissionDTO);
        log.info("微信红包发送请求返回 wechatTransferResp==="+ JSON.toJSONString(wechatTransferResp));
        if (ObjectUtil.isEmpty(wechatTransferResp)){
            rewardsLog.setStatus(CommonStatusEnum.DISABLE.getCode());
            rewardsLog.setDetailStatus(WechatConstant.RESP_FAIL_MSG);
            baseMapper.insert(rewardsLog);
            return;
        }
        if (ObjectUtil.notEqual(WechatConstant.RESP_SUCCESS_CODE_200, wechatTransferResp.getCode())){
            rewardsLog.setStatus(CommonStatusEnum.DISABLE.getCode());
            rewardsLog.setDetailStatus(WechatConstant.RESP_FAIL_MSG);
        }else {
            rewardsLog.setStatus(CommonStatusEnum.ENABLE.getCode());
            rewardsLog.setDetailStatus(WechatConstant.RESP_SUCCESS_MSG);
        }
        baseMapper.insert(rewardsLog);
    }


    /**
     * 生成商户订单号，规则为：{来源编号(4位)}{时间(yyyyMMddmmHHssSSS)(17位)}{7位随机数}
     *
     * @return
     */
    private String getMerNum() {
        String dateTime = DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATETIME_MS_PATTERN);
        return dateTime + RandomStringUtils.randomNumeric(3);
    }
}
